<template>
  <div>
    <el-container>
      <el-header class="inside-header">
        <div>
          <!-- 面包屑 -->
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>车辆备案</el-breadcrumb-item>
            <el-breadcrumb-item class="breadcrumbColor">运输车辆备案</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-header>
      <el-main>
        <div class="inside-main-box">
          <el-row class="inside-main" style="height: 40px">
            <el-col :span="5" style="margin-left: 20px">
              <el-form-item label="申请时间" size="small">
                <el-date-picker clearable v-model="form.startDateTime" style="width: 100%" type="date" placeholder="选择时间" />
              </el-form-item>
            </el-col>
            <span>-</span>
            <el-col :span="4">
              <el-form-item label="" size="small">
                <el-date-picker clearable v-model="form.endDateTime" type="date" placeholder="选择时间" style="width: 92%"/>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="margin-left: 5px">
              <el-form-item label="车牌号" size="small">
                <el-input clearable v-model="form.cl_cph" maxLength="8" placeholder="请输入车牌号" />
              </el-form-item>
            </el-col>
            <el-col :span="4" style="margin-left: 15px">
              <el-form-item label="司机" size="small">
                <el-input clearable v-model="form.sj_name" maxLength="8" placeholder="请输入司机" />
              </el-form-item>
            </el-col>
            <el-col :span="4" style="margin-left: 20px">
              <el-button size="small" class="sele-but" icon="search" @click="selectQ">查询</el-button>
              <el-button size="small" class="empty-but" icon="refresh" @click="onReset">重置</el-button>
            </el-col>
          </el-row>
          <div></div>
        </div>
        <div style="height: 45px; display: flex; align-items: center;background:#f2f4f5;margin:0 -19.5px 0 -20px">
          <el-button size="small" icon="plus" class="add-but" @click="addPage()" style="margin-left:20px">新增</el-button>
          <el-button type="danger" plain size="small" icon="delete" @click="deleteAll">删除</el-button>
          <el-button size="small" class="empty-but" icon="upload" @click="dialogTableVisible = true">导入</el-button>
          <el-button size="small" class="empty-but" icon="download" @click="exportExcelData(form)">导出</el-button>
        </div>
        <div>
          <el-table :data="tableData"  style="width: 100%;" height="460" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column align="center" label="序号" type="index" width="80px" show-overflow-tooltip/>
            <el-table-column align="center" prop="sj_name" label="司机"  show-overflow-tooltip/>
            <el-table-column align="center" prop="cl_cph" label="车牌"  show-overflow-tooltip/>
            <el-table-column align="center" prop="drivingLicense" label="行驶证正本">
              <template #default="scope">
                <el-button v-if="scope.row.vehicleMessage?.drivingLicense==''||scope.row.vehicleMessage?.drivingLicense== null" type="primary" size="small" link >未上传
               </el-button>
                 <el-button v-else type="primary" size="small" link @click="drivingLicenselist(scope.row)">查看照片
               </el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="vehiclePhoto" label="行驶证副本" >
              <template #default="scope">
                <el-button  v-if="scope.row.vehicleMessage?.vehiclePhoto==''||scope.row.vehicleMessage?.vehiclePhoto== null" type="primary" size="small" link >未上传</el-button>
              <el-button  v-else  type="primary" size="small" link @click="vehiclelist(scope.row)">查看图片</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="accompanyingList" label="随车清单">
              <template #default="scope">
                <el-button v-if="scope.row.vehicleMessage?.accompanyingList==''||scope.row.vehicleMessage?.accompanyingList== null" link type="primary" size="small">未上传
               </el-button>
               <el-button  v-else type="primary" size="small" link @click="acclist(scope.row)">查看照片
               </el-button>
              </template>
            </el-table-column>

            <el-table-column align="center" prop="applicationTime" label="申请时间" width="200px" show-overflow-tooltip/>
            <el-table-column align="center" prop="vehicleEmissions" label="排放阶段" show-overflow-tooltip>
              <template #default="scope">
                <span>{{ scope.row.vehicleEmissions }}</span>
              </template>
            </el-table-column>
            <!--
            <el-table-column align="center" prop="typeOfAcces" label="出入类型" show-overflow-tooltip>
              <template #default="scope">
                <span>{{ scope.row.typeOfAcces }}</span>
              </template>
            </el-table-column>
            -->
            <el-table-column align="center" fixed="right" label="操作" width="240px">
              <template #default="scope">
                <el-button link type="primary" size="small" icon="view" @click="detailPage(scope.row)">详情</el-button>
                <el-button link type="primary" size="small" icon="edit" @click="update(scope.row)">修改</el-button>
                <!--<el-button link type="danger"  size="small" icon="delete" @click="delect(scope.row)">删除</el-button>-->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="margin-right:40px; display: flex; justify-content: flex-end"  v-model:current-page="queryInfo.pagenum" v-model:page-size="queryInfo.pagesize"
           size="small"   layout="prev, pager, next, jumper,total"
           :total="queryInfo.total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
        </div>
      </el-main>
    </el-container>
    <!--查看照片弹窗-->
     <el-dialog v-model="vehiclePhotoDia"  center>
          <div class="photoDiv" >
           <img class="photoImg" :src='Image.vehiclePhoto' alt=""/></div>
        </el-dialog>
        <el-dialog v-model="accompanyingListDia"  center>
          <div class="photoDiv">
           <img class="photoImg" :src='Image.accompanyingList' alt=""/></div>
        </el-dialog>
                <el-dialog v-model="drivingLicenseDia"  center>
          <div class="photoDiv">
           <img class="photoImg" :src='Image.drivingLicense' alt=""/></div>
        </el-dialog>

            <!-- 导入弹出框 -->
        <el-dialog style="width: 600px" v-model="dialogTableVisible" center title="导入文件">
          <el-upload ref="uploadFile" :file-list="state.fileList" class="upload-demo" action='#'
                  accept=".xls" drag :http-request="uploadAction" :on-exceed="handleExceed" :limit="1"
                  :show-file-list="false" :auto-upload="true" :before-upload="beforeUpload" style="width: 100%;">
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件托到此处或<em>点击导入</em>
            </div>
            <template #tip>
              <div style="text-align:center;margin-top:10px">
               <p style="font-size:14px;">支持上传xsl格式文件,如果没有模板
               <a style="text-decoration:none;" href="template/运输车辆导入模板.xls" download>
               <el-button link  type="primary" size="mini">点击下载</el-button></a>>
              </p>
              </div>
            </template>
          </el-upload>
        </el-dialog>
  </div>
</template>

<script>
import { onMounted, reactive, ref, defineEmits } from "vue";
import { Plus, UploadFilled } from "@element-plus/icons-vue";
import { selectAll, selectQuery, deleteData,uploadExcel,deleteAllTransportVehicles  } from "@/api/mobilePollution";
import { vehiclesListOut } from "@/api/leadingOut"
import car from "@/assets/car.png";
// 路由
import { useRouter } from "vue-router";
// 文件导入
import { ElMessage, ElMessageBox } from "element-plus";
import * as XLSX from "xlsx";
import moment from "moment";
import { v3ImgPreviewFn } from 'v3-img-preview'
export default {
  setup() {
    onMounted(() => {
      selectQ();
      localStorage.removeItem("userObj");
    });
    // 跳转到修改页面
    const router = useRouter();
    const update = (row) => {
      localStorage.setItem("userObj", JSON.stringify(row));
      router.push({
        path: "/transportUpdate",
        // params: { parameter: JSON.stringify(row) },
        // name: "transportAdd",
        // query: { id: 2 },
        query: { id: JSON.stringify(row.cl_id),}
      });
    };
    const multipleSelection = ref([])
    const handleSelectionChange = (val) => {
      multipleSelection.value = val
    }
    const deleteAll = () => {
        if (multipleSelection.value.length == 0){
          ElMessage.error("请选择要删除的数据")
        }else {
          ElMessageBox.confirm("确定删除吗?").then(()=>{
          deleteAllTransportVehicles(multipleSelection.value).then((res) => {
            if(res.code == 200){
              ElMessage.success("删除成功!")
              selectQ()
            }else {
              ElMessage.error('删除失败')
            }
          })
        })
        }
    }
    let table = reactive({
      rows: [],
      total: 0,
    });
    const tableData = ref([]);
    //分页
    const queryInfo = reactive({
      pagenum:1,
      pagesize:10,
      total:0
    })
    const handleSizeChange = (val) => {
      queryInfo.pagesize = val
      selectQ()
    }
    //点击第几页
    const handleCurrentChange = (val) => {
      queryInfo.pagenum = val
      selectQ()
    }
    // console.log(process.env.VUE_APP_BASE_API,'服务Ip')
    //查询所有
    // const select = () => {
    //   selectQuery({pageNum:queryInfo.pagenum,pageSize:queryInfo.pagesize}).then((res) => {
    //     if (res.code == 200) {
    //       tableData.value = res.data.list;
    //       queryInfo.total=res.data.total;
    //     } else {
    //     }
    //   });
    // };
    //搜索查询
    const selectQ = () => {
      localStorage.removeItem("userObj");
      if (form.startDateTime){
        let startDate = moment(form.startDateTime).format('YYYY-MM-DD')
        form.startDateTime =  startDate
      }
      if (form.endDateTime){
        let endDate = moment(form.endDateTime).format('YYYY-MM-DD')
        form.endDateTime =  endDate
      }
      if (form.startDateTime === 'Invalid date'){
        form.startDateTime = ''
      }
      if (form.endDateTime === 'Invalid date'){
        form.endDateTime = ''
      }
      form.pageSize = queryInfo.pagesize
      form.pageNum = queryInfo.pagenum
      selectQuery(form).then((res) => {
        if (res.code == 200) {
          tableData.value = res.data.list;
          queryInfo.total=res.data.total;
        } else {

        }
      });
    };
    //删除
    const delect = (row) => {
      ElMessageBox.confirm("确定删除吗?").then(()=>{
        deleteData(row).then((res) => {
          selectQ();
        });
      })
    };
    const Image = reactive({
      vehiclePhoto:"",
      accompanyingList:"",
      drivingLicense:"",

    })
    //行驶证副本显示图片
    const vehiclePhotoDia = ref(false);
    const vehiclelist = (row) => {
      // vehiclePhotoDia.value = true;
      Image.vehiclePhoto = `${process.env.VUE_APP_BASE_API}\/${row.vehicleMessage.vehiclePhoto}`
      v3ImgPreviewFn(Image.vehiclePhoto)
    };
    //随车清单显示图片
    const accompanyingListDia = ref(false);
    const acclist = (row) => {
      // accompanyingListDia.value = true;
      Image.accompanyingList = `${process.env.VUE_APP_BASE_API}\/${row.vehicleMessage.accompanyingList}`
      v3ImgPreviewFn(Image.accompanyingList)
    };
    //行驶证正本显示图片
    const drivingLicenseDia = ref(false);
    const drivingLicenselist = (row) => {
      // drivingLicenseDia.value = true;
      Image.drivingLicense = `${process.env.VUE_APP_BASE_API}\/${row.vehicleMessage.drivingLicense}`
      v3ImgPreviewFn(Image.drivingLicense)
    };

    // 导入
    const uploadFile = ref();
    const state = reactive({
      bannerUrl: '',
      fileList: [],
      fileName: '',
    })

    const clearFiles = () => {
      ref.uploadFile.clearFiles();
    }
    const beforeUpload = (file) => {
      // const type = ['image/jpeg', 'image/jpg', 'image/png']
      // const type = ['application/vnd.ms-excel']
      // if (type.indexOf(file.type) === -1) {
      //   ElMessage.error('上传的文件必须是xls,xlsx')
      //   return false
      // } else if (file.size / 1024 / 1024 > 2) {
      //   ElMessage.error('文件大小不能超过2MB!')
      //   return false
      // }
    }
    const handleExceed = (files, fileList) => {
      if (state.fileList.length >= 1) {
        ElMessage.error('只能上传一个文件')
        return;
      }
    }
    const uploadAction = (option) => {
      let param = new FormData();
      param.append('multipartFile', option.file);
      uploadExcel(param).then((res) => {
        if (res && res.code === 200) {
          state.fileList = []
          dialogTableVisible.value = false
          ElMessage.success(res.data);
          selectQ()
        }else if(res.code == 701){
          state.fileList = []
          dialogTableVisible.value = false
          ElMessage.error(res.data)
        }else if(res.code == 605){
          state.fileList = []
          dialogTableVisible.value = false
          ElMessage.error(res.data)
        }else{
          state.fileList = []
          dialogTableVisible.value = false
          ElMessage.error('文件导入失败')
        }
      }).catch(error => {
        state.fileList = []
        dialogTableVisible.value = false
        ElMessage.error('文件导入失败')
      });

    }
    // 导入弹出框
    const dialogTableVisible = ref(false);
    // 新增跳转到新增页面
    const addPage = () => {
      router.push({
        path: "/transportAdd",
        // query: { id: "1" },
      });
    };
    const a = ref("1");
    // 重置
    const onReset = () => {
      form.startDateTime = "";
      form.endDateTime = "";
      form.sj_name = "";
      form.cl_cph = "";
      form.typeOfAcces = "";
      selectQ()
    };
    // 跳转到详情页面
    const detailPage = (row) => {
      localStorage.setItem("userObj", JSON.stringify(row));
      router.push({
        path: "/transportDetail",
        query: { id: JSON.stringify(row.cl_id),}
      });
    };
    const name = "transportIndex";
    // 时间
    const size = ref("default");
    const form = reactive({
      startDateTime: "",
      endDateTime: "",
      sj_name: "",
      cl_cph: "",
      typeOfAcces: "",
      pageNum: queryInfo.pagenum,
      pageSize: queryInfo.pagesize
    });
    //导出英文(数据库字段)
    // const exportExcel = () => {
    //   console.log(tableData.value,'tableData')
    //   const data = XLSX.utils.json_to_sheet(tableData.value); //此处tableData.value为表格的数据
    //   const wb = XLSX.utils.book_new();
    //   XLSX.utils.book_append_sheet(wb, data, "test-data"); //test-data为自定义的sheet表名
    //   XLSX.writeFile(wb, "运输车辆备案.xlsx"); //test.xlsx为自定义的文件名
    // };
//导出工序(中文)
    const exportExcelData = (form) => {
      ElMessageBox.confirm("确定要导出吗?").then(() => {
        vehiclesListOut(form).then((res) => {
          if (res.data.length == 0){
            ElMessage.error("未查询到数据")
          }else {
            out.value = res.data
            exportExcel()
          }
        })
      })
    }
    const out = ref()
    const exportExcel = () => {

      let exportData = []
      //导出数据结构构造
      out.value.forEach(item => {
        exportData.push({
          typeOfAcces:item.typeOfAcces ? item.typeOfAcces : '',
          cl_cph: item.cl_cph? item.cl_cph : '',
          sj_name: item.sj_name ? item.sj_name : '',
          sj_phone: item.vehicleMessage.sj_phone ? item.vehicleMessage.sj_phone : '',
          cl_tihuodanwei : item.register.cl_tihuodanwei ? item.register.cl_tihuodanwei : '',
          cl_cz : item.vehicleMessage.cl_cz ? item.vehicleMessage.cl_cz : '',
          natureOfVehicleUse : item.vehicleMessage.natureOfVehicleUse ? item.vehicleMessage.natureOfVehicleUse : '',
          cl_dz : item.vehicleMessage.cl_dz ? item.vehicleMessage.cl_dz : '' ,
          registernDate: item.vehicleMessage.registernDate ? item.vehicleMessage.registernDate : '',
          certificateDate: item.vehicleMessage.certificateDate ? item.vehicleMessage.certificateDate : '',
          licensePlateColor: item.vehicleMessage.licensePlateColor ? item.vehicleMessage.licensePlateColor : '',
          modeldescription: item.vehicleMessage.modeldescription ? item.vehicleMessage.modeldescription: '',
          vehicleFuel: item.vehicleMessage.vehicleFuel ? item.vehicleMessage.vehicleFuel: '',
          cl_ppxh: item.vehicleMessage.cl_ppxh ? item.vehicleMessage.cl_ppxh: '',
          vehicleEmissions: item.vehicleEmissions ? item.vehicleEmissions: '',
          cl_sbm: item.vehicleMessage.cl_sbm ? item.vehicleMessage.cl_sbm : '',
          cl_fdjhm: item.vehicleMessage.cl_fdjhm ? item.vehicleMessage.cl_fdjhm : '',
          cl_fdjxh: item.vehicleMessage.cl_fdjxh ? item.vehicleMessage.cl_fdjxh : '',
          cl_hdzzl: item.vehicleMessage.cl_hdzzl ? item.vehicleMessage.cl_hdzzl : '',
          obdInstallation :item.vehicleMessage.obdInstallation ? item.vehicleMessage.obdInstallation: '',
          accompanyingList: item.vehicleMessage.accompanyingList ? item.vehicleMessage.accompanyingList: '',
          drivingLicense:item.vehicleMessage.drivingLicense ? item.vehicleMessage.drivingLicense : '',
          vehiclePhoto:item.vehicleMessage.vehiclePhoto ? item.vehicleMessage.vehiclePhoto: ''
        })
      })
      //导出表头设计
      let head = {
        typeOfAcces:'出厂类型',
        cl_cph: '车牌号',
        sj_name: '联系人',
        sj_phone:'联系电话',
        cl_tihuodanwei:'送/提货单位',
        cl_cz:'所有人',
        natureOfVehicleUse:'使用性质',
        cl_dz:'住址',
        registernDate:'注册日期',
        certificateDate:'发证日期',
        licensePlateColor:'车牌颜色',
        modeldescription:'车辆类型',
        vehicleFuel:'燃料类型',
        cl_ppxh:'品牌型号',
        vehicleEmissions:'排放阶段',
        cl_sbm:'车辆识别代码(VIN)',
        cl_fdjhm:'发动机号码',
        cl_fdjxh:'发动机型号',
        cl_hdzzl:'核定载质量(T)',
        obdInstallation:'是否安装OBD',
        accompanyingList:'随车清单',
        drivingLicense:'行驶证正本',
        vehiclePhoto:'行驶证副本'
      }
      //表头数据切换
      const list = exportData.map(item => {
        const obj = {}
        for (const k in item) {
          if (head[k]) {
            obj[head[k]] = item[k]
          }
        }
        return obj
      })
      // 创建工作表
      const data = XLSX.utils.json_to_sheet(list)
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      // 将工作表放入工作簿中
      XLSX.utils.book_append_sheet(wb, data, 'data')
      // 生成文件并下载
      XLSX.writeFile(wb, '运输车辆备案.xlsx')

    }
    return {
      exportExcelData,
      queryInfo,
      handleSizeChange,
      handleCurrentChange,
      form,
      onReset,
      exportExcel,
      dialogTableVisible,
      uploadAction,
      beforeUpload,
      handleExceed,
      clearFiles,
      state,
      tableData,
      // select,
      addPage,
      selectQ,
      update,
      detailPage,
      delect,
      Image,
      vehiclelist,
      vehiclePhotoDia,
      acclist,
      accompanyingListDia,
      drivingLicenselist,
    drivingLicenseDia,
      multipleSelection,
      handleSelectionChange,
      deleteAll
    };
  },
  mounted(){
    window.vue = this
  },
};
</script>
<style scoped>
/* 面包屑字体颜色更改 */

.breadcrumbColor >>> .el-breadcrumb__inner {
  color: #000;
}
/* 内部header */

.inside-header {
  height: 20px;
  display: flex;
  justify-content: left;
  align-items: flex-start;
  background:#f2f4f5
}
/* 空心按钮样式 */

.empty-but {
  border: 1px solid #3780b9;
  color: #3780b9;
}
/* 实心按钮背景样式 */

.sele-but {
  background: #3780b9;
  border: 0px;
  border-radius: 2px;
  color: white;
}

.add-but {
  background: #dde5fe;
  color: #3780b9;
}
/*照片弹窗及图片样式*/
.photoImg{
  vertical-align: middle;width:100%;height:600px;margin:auto
}
.photoDiv{
  width:100%;
  display:flex
}
/* 分页 */

.demo-pagination-block {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
